<template>
  <admin-container title="产品添加" class="artcie-form-container">
    <div class="form">
      <el-form size="small" :model="form" ref="form" label-width="120px" :rules="rules">
        <el-form-item label="产品分类">
          <el-select v-model="form.categoryId">
            <el-option v-for="item in categorys" :key="item.id" :value="item.id" :label="item.categoryName"></el-option>
          </el-select>
          <div class="select-button">
            <el-button type="text" size="medium" icon="el-icon-refresh-left" @click="getAllProductCategor">刷新</el-button>
          </div>
        </el-form-item>
        <el-form-item label="产品编号">
          <el-input v-model="form.productID" placeholder="请输入产品编号，支持数字英文" maxlength="50" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="产品名称" prop="productName">
          <el-input v-model="form.productName" placeholder="请输入产品名称" maxlength="100" show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="Product Name">
          <el-input v-model="form.productNameEn" placeholder="Please enter the product name" maxlength="255"
            show-word-limit></el-input>
        </el-form-item>
        <el-form-item label="产品图片">
          <div class="emphasis">
            <div class="tip">
              至少上传一张图片,第一张图片会默认设为产品主图，最多可上传6张图片，推荐尺寸 480 * 480 1:1 图片大小不能超过2mb
            </div>
            <div>
              <image-upload :max="6" :default-imags="form.images" @upload-images="handleUploadImage"></image-upload>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="零售价格">
          <el-select style="width: 80px;" v-model="form.currencies" placeholder="货币">
            <el-option v-for="item in currencies" :key="item.id" :label="item.unit" :value="item.id">
            </el-option>
          </el-select>
          <el-input-number style="width: 200px;" v-model="form.price" :precision="2" :step="1"></el-input-number>
          / <el-input v-model="form.unit" style="width: 80px;" placeholder="单位"></el-input>
          <el-input v-model="form.unitEn" style="width: 80px;" placeholder="Unit"></el-input>
          <div class="showPrice">
            <label>显示价格</label>
            <el-switch v-model="form.showPrice">
            </el-switch>
          </div>
          <div class="showPrice">
            <label>首页展示</label>
            <el-switch v-model="form.homeShow">
            </el-switch>
          </div>
          <div class="form-set">
            <div class="form-set-item">
              <label>上架</label>
              <el-switch v-model="form.publish">
              </el-switch>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="简单描述">
          <div class="emphasis">
            <el-input type="textarea" :maxlength="500" show-word-limit :rows="6" v-model="form.shortDescription"
              placeholder="简单描述一下产品的特点"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="Description">
          <div class="emphasis">
            <el-input type="textarea" :maxlength="1000" show-word-limit :rows="6" v-model="form.shortDescriptionEn"
              placeholder="Briefly describe the features of the product"></el-input>
          </div>
        </el-form-item>
        <el-form-item label="产品详情">
          <div class="editor">
            <Toolbar style="border-bottom: 1px solid #DCDFE6" :editor="editor" :defaultConfig="toolbarConfig"
              :mode="mode" />
            <Editor style="height: 500px; overflow-y: hidden;" v-model="form.longDescription"
              :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreated" />
          </div>
        </el-form-item>
        <el-form-item label="Product Details">
          <div class="editor">
            <Toolbar style="border-bottom: 1px solid #DCDFE6" :editor="editorEn" :mode="mode" />
            <Editor style="height: 500px; overflow-y: hidden;" v-model="form.longDescriptionEn"
              :defaultConfig="editorConfig" :mode="mode" @onCreated="onCreatedEn" />
          </div>
        </el-form-item>
      </el-form>
      <div class="fix-buttons">
        <div class="button-group">
          <template v-if="form.id != 0">
            <el-button size="small" type="primary" @click="handleUpdate"><i class="el-icon-check"></i> 修改保存</el-button>
            <el-button size="small" type="danger"><i class="el-icon-delete"></i> 删除产品</el-button>
          </template>
          <template v-else>
            <el-button size="small" type="primary" @click="handleSubmit"><i class="el-icon-check"></i> 提交保存</el-button>
          </template>
        </div>
      </div>
    </div>
  </admin-container>
</template>

<script>
import AdminContainer from '@/components/Admin/AdminContainer.vue';
import ImageUpload from '@/components/ImageUpload.vue';
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import '@wangeditor/editor/dist/css/style.css';
import * as productApi from '@/api/admin/productApi'
import * as productCategorieApi from '@/api/admin/productCategorieApi'
import * as productPriceCurrenciesApi from '@/api/admin/productPriceCurrenciesApi'
import * as storage from '@/utils/localStorageUtil';

export default {
  components: {
    AdminContainer,
    ImageUpload,
    Editor,
    Toolbar
  },
  data () {
    return {
      form: {
        id: 0,
        images: [],
        price: 0,
        shortDescription: "",
        publish: true,
        longDescription: "",
        categoryId: 1,
        productName: "",
        showPrice: true,
        productID: "",
        productNameEn: "",
        shortDescriptionEn: "",
        longDescriptionEn: "",
        currencies: "HKD",
        unit: "",
        unitEn: "",
        homeShow: false,
      },
      errors: {
        images: ""
      },
      rules: {
        productName: [
          { required: true, message: '商品标题不能为空', trigger: 'blur' }
        ],
        images: [
          {
            validator: (rule, value, callback) => {
              if (value.length === 0) {
                callback(new Error('商品图片不能为空'))
                this.errors.images = '至少上传一张图片';
              } else {
                callback()
                this.errors.images = '';
              }
            },
            trigger: 'change',
            required: true
          }
        ]
      },
      editor: null,
      editorEn: null,
      toolbarConfig: {},
      editorConfig: {
        placeholder: '请输入内容...',
        MENU_CONF: {
          uploadVideo: {
            server: process.env.API_ROOT + '/api/admin/Article/UploadMedia',
            fieldName: "mediaFile",
            maxNumberOfFiles: 1,
            headers: {
              Authorization: storage.getLocalStorage('francis:jwt')
            },
            onError: function (xhr, err) {
              self.$message.error(err.message);
            },
          },
          uploadImage: {
            server: process.env.API_ROOT + '/api/admin/Article/UploadMedia',
            fieldName: 'mediaFile',
            maxNumberOfFiles: 1,
            headers: {
              Authorization: storage.getLocalStorage('francis:jwt')
            },
            onError: function (xhr, err) {
              if (err.message.indexOf('exceeds') > -1) {
                self.$message.error('上传的图片大小不能大于2mb');
              }
              else {
                self.$message.error(err.message);
              }
            },
          }
        },
      },
      mode: 'default',
      categorys: [],
      currencies: []
    }
  },
  methods: {
    handleSubmit () {
      var self = this;
      self.$refs['form'].validate(valid => {
        if (valid) {
          productApi.add(self.form)
            .then(res => {
              if (res.code == 200) {
                self.$message({
                  message: '保存成功',
                  type: 'success'
                });
                self.$router.push({ path: '/management/product/list' });
              }
              else if (res.code == 500) {
                self.$message.error(res.exception);
              }
            })
            .catch(err => {
              self.$message.error('保存失败，接口出错');
            })
        } else {
          return false
        }
      })
    },
    handleUploadImage (images) {
      this.form.images = images;
    },
    handleGetProductSingleById () {
      var self = this;
      if (self.form.id != 0) {
        productApi.getProductSingleById(self.form.id)
          .then(res => {
            if (res.code == 200) {
              self.form = res.data;
            }
            else if (res.code == 500) {
              self.$message.error(res.exception);
            }
          })
          .catch(err => {
            self.$message.error('接口出现错误');
          })
      }
    },
    onCreated (editor) {
      this.editor = Object.seal(editor);
    },
    onCreatedEn (editor) {
      this.editorEn = Object.seal(editor);
    },
    handleUpdate () {
      var self = this;
      self.$refs['form'].validate(valid => {
        if (valid) {
          productApi.updateProduct(self.form)
            .then(res => {
              if (res.code == 200) {
                self.$message({
                  message: '更新成功',
                  type: 'success'
                });
                self.$router.push({ path: '/management/product/list' });
              }
              else if (res.code == 500) {
                self.$message.error(res.exception);
              }
            })
            .catch(err => {
              self.$message.error('更新失败，接口出错');
            })
        } else {
          return false
        }
      })
    },
    getAllProductCategor () {
      var self = this;
      productCategorieApi.getAllProductCategories()
        .then(res => {
          if (res.code == 200) {
            self.categorys = res.data;
          }
          else if (res.code == 500) {
            self.$message.error(res.exception);
          }
        })
        .catch(err => {
          self.$message.error('保存失败，接口出错');
        })
    },
    openEditCategory () {
      // 在新窗口中打开路由页面
      window.open('/management/Product/categorie', '_blank');
    },
    getAllProductPriceCurrencies () {
      var self = this;
      productPriceCurrenciesApi.getAllProductPriceCurrencies()
        .then(res => {
          if (res.code == 200) {
            self.currencies = res.data;
          }
          else if (res.code == 500) {
            self.$message.error(res.exception);
          }
        })
        .catch(err => {
          self.$message.error('保存失败，接口出错');
        })
    },
  },
  mounted () {
    var self = this;
    self.getAllProductCategor();
    self.getAllProductPriceCurrencies();
    if (self.$route.query.id != null) {
      self.form.id = parseInt(self.$route.query.id);
      self.handleGetProductSingleById();
    }
  },
  beforeDestroy () {
    const editor = this.editor
    if (editor == null) return
    editor.destroy() // 组件销毁时，及时销毁编辑器
  }
}
</script>

<style scoped>
.form {
  padding-top: 50px;
  position: relative;
}

.tip {
  padding: 0px 16px;
  background-color: #ecf8ff;
  border-radius: 4px;
  border-left: 5px solid #50bfff;
  color: #5e6d82;
}

.emphasis {
  background-color: #f7f8fa;
  padding: 10px;
}

.editor {
  border: 1px solid #DCDFE6;
}

.fix-buttons {
  /* background: #eee; */
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  padding-left: 200px;
}

.button-group {
  text-align: center;
  padding: 15px 0px;
  border-top: 1px solid #EBEEF5;
  background: #f7f8fa;
}

.button-group .el-button+.el-button {
  margin-left: 1px;
}

.artcie-form-container {
  margin-bottom: 65px !important;
}

.form-set {
  display: inline-block;
  margin-left: 10px;
}

.form-set-item label {
  margin-right: 10px;
}

.form-set-item+.form-set-item {
  margin-left: 20px;
}

.showPrice {
  margin-left: 10px;
  display: inline-block;
}

.select-button {
  margin-left: 10px;
  display: inline-block;
}

.select-button .el-button+.el-button {
  margin-left: 5px;
}
</style>